package net.sf.midollo.midlet;

import java.io.IOException;

import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDletStateChangeException;

import net.sf.midollo.io.lcdui.textbox.TextBoxOutputStream;
import net.sf.midollo.midlet.common.BaseMIDlet;
import net.sf.midollo.net.protocol.echo.EchoFactory;
import net.sf.midollo.net.server.AsyncAcceptHandler;
import net.sf.midollo.net.server.InetServer;
import net.sf.midollo.utils.MidpUtils;

public class EchoSrv extends BaseMIDlet {

  protected InetServer inetServer;

  public void run() {
    try {
      TextBox textBox = new TextBox("EchoSrv", null, 8000, 0);
      MidpUtils.LOG_STREAM = new TextBoxOutputStream(textBox);

      textBox.addCommand(this.exitCommand);
      textBox.setCommandListener(this);
      this.display.setCurrent(textBox);

      final int serverPort = 64080;

      EchoFactory protocolFactory = new EchoFactory(32);
      AsyncAcceptHandler acceptHandler = new AsyncAcceptHandler(protocolFactory);
      this.inetServer = new InetServer(serverPort, acceptHandler);
      this.inetServer.runServer();
    } catch (Exception ex) {
      MidpUtils.showError(this.display, ex);
    }
  }

  protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    if (this.inetServer != null) {
      try {
        this.inetServer.close();
      } catch (IOException ex) {
      }
    }
    super.destroyApp(unconditional);
  }
}
